package com.cloudloan.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudloan.common.R;
import com.cloudloan.entity.LoginUser;
import com.cloudloan.entity.User;
import com.cloudloan.mapper.LoginMapper;
import com.cloudloan.service.LoginServcie;
import com.cloudloan.utils.AdministratorThreadLocal;
import com.cloudloan.utils.JwtUtil;
import com.cloudloan.utils.RedisUtils;
import com.cloudloan.utils.SaltMD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Objects;

@Transactional
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper,User> implements LoginServcie {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private LoginMapper loginMapper;
    @Override
    public R login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getPhone(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        LoginUser principal = (LoginUser)authenticate.getPrincipal();
        User sysuser = principal.getUser();
        if(sysuser.getStatus()==2){
            return R.error("此用户已被禁用");
        }
        sysuser.setPassword(null);
        String phone = sysuser.getPhone();
        String jwt = JwtUtil.createJWT(phone);
        redisUtils.setCacheObject("login:"+sysuser.getPhone(),sysuser);
        HashMap<String,Object> map=new HashMap<>();
        map.put("token",jwt);
        map.put("user",sysuser);
        return R.success(map, "登录成功");
    }

    /**
     * 退出登录
     * @return
     */
    @Override
    public R logout() {
        //获取SecurityContextHolder中的用户id
        User sysUser = AdministratorThreadLocal.getAdministrator();
        String phone = sysUser.getPhone();
        AdministratorThreadLocal.removeAdministrator();
        redisUtils.deleteObject("login:"+phone);
        return R.success("退出成功");
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public R sava(User user) {
        //密码加密
        String password = SaltMD5Utils.generateSaltPassword(user.getPassword());
        user.setPassword(password);
        return loginMapper.insert(user)>0?R.success("成功"):R.error("失败");
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @Override
    public R selectId(Long id) {
        User user = loginMapper.selectById(id);
        if(user==null){
            R.error("未根据id查询出用户信息");
        }
        user.setPassword(null);
        return R.success(user);
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @Override
    public R updateId(User user) {
        if(user.getPassword()!=null&&!user.getPassword().equals("")){
            String password = SaltMD5Utils.generateSaltPassword(user.getPassword());
            user.setPassword(password);
        }
        return loginMapper.updateById(user)>0?R.success("修改成功"):R.error("修改失败");
    }
}
